#include "metadata.h"
#include "dbs.h"
#include "DbsSqlite3.h"
#include <mutex>


struct Metadata::MetadataImpl
{
    std::string table;
    std::mutex mtx;
    std::shared_ptr<Dbs> db;
};

Metadata::Metadata()
{
    m_impl = new MetadataImpl;
}

Metadata::~Metadata()
{
    delete m_impl;
}

bool Metadata::Open(int dbType)
{
    bool res{ false };
    switch (dbType)
    {
    case DB_SQLITE:
        m_impl->db = std::make_shared<DbsSqlite3>();
        res = m_impl->db->Open();
        break;
    default:
        break;
    }
    return false;
}

void Metadata::Close()
{
    m_impl->db->Close();
}

bool Metadata::MakeTable()
{
    bool res = false;
    int count{ -1 };
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        count = m_impl->db->MakeTable();
    } while (0);
    return count;
}

void Metadata::SetTableName(const std::string & name)
{
    m_impl->db->SetTableName(name);
}

int Metadata::SelectFileInfo(const std::string& relative, StFileInfo & info)
{
    bool res = false;
    int count{ -1 };
    do 
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        count = m_impl->db->SelectFileInfo(relative, info);
    } while (0);
    return count;
}

bool Metadata::InsertFileInfo(StFileInfo* info, int size)
{
    bool res = false;
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        if (!m_impl->db->InsertFileInfo(info, size))
        {
            break;
        }
        res = true;
    } while (0);
    return res;
}

bool Metadata::UpdateFileInfo(StFileInfo* info, int size)
{
    bool res = false;
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        if (!m_impl->db->UpdateFileInfo(info, size))
        {
            break;
        }
        res = true;
    } while (0);
    return res;
}

bool Metadata::SelectFileLatestPacket(int64_t& packet)
{
    bool res = false;
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        if (!m_impl->db->SelectFileLatestPacket(packet))
        {
            break;
        }
        res = true;
    } while (0);
    return res;
}

int Metadata::SelectVersionInfo(const std::string& app, StVersionInfo& info)
{
    bool res = false;
    int count{ -1 };
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        count = m_impl->db->SelectVersionInfo(app, info);
    } while (0);
    return count;
}

bool Metadata::InsertVersionInfo(const StVersionInfo& info)
{
    bool res = false;
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        if (!m_impl->db->InsertVersionInfo(info))
        {
            break;
        }
        res = true;
    } while (0);
    return res;
}

bool Metadata::UpdateVersionInfo(const StVersionInfo& info)
{
    bool res = false;
    do
    {
        std::lock_guard<std::mutex> lck(m_impl->mtx);
        if (!m_impl->db->UpdateVersionInfo(info))
        {
            break;
        }
        res = true;
    } while (0);
    return res;
}
